import hashlib
import secrets
from typing import BinaryIO

class HashUtils:
    """哈希处理工具类"""
    
    @staticmethod
    def calculate_md5(file_obj: BinaryIO) -> str:
        """计算文件MD5哈希值"""
        hash_md5 = hashlib.md5()
        file_obj.seek(0)  # 重置文件指针
        
        for chunk in iter(lambda: file_obj.read(4096), b""):
            hash_md5.update(chunk)
        
        file_obj.seek(0)  # 重置文件指针
        return hash_md5.hexdigest()
    
    @staticmethod
    def calculate_sha256(file_obj: BinaryIO) -> str:
        """计算文件SHA256哈希值"""
        hash_sha256 = hashlib.sha256()
        file_obj.seek(0)  # 重置文件指针
        
        for chunk in iter(lambda: file_obj.read(4096), b""):
            hash_sha256.update(chunk)
        
        file_obj.seek(0)  # 重置文件指针
        return hash_sha256.hexdigest()
    
    @staticmethod
    def generate_share_token() -> str:
        """生成分享令牌"""
        return 'sh_' + secrets.token_urlsafe(8)
    
    @staticmethod
    def generate_preview_token() -> str:
        """生成预览令牌"""
        return 'pv_' + secrets.token_urlsafe(16)
    
    @staticmethod
    def verify_md5(file_obj: BinaryIO, expected_md5: str) -> bool:
        """验证文件MD5值"""
        actual_md5 = HashUtils.calculate_md5(file_obj)
        return actual_md5.lower() == expected_md5.lower()